package com.ja.openchat.ui.chat;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.BuildConfig;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityForwardBinding;
import com.ja.openchat.ui.chat.listener.OnContactSendListener;
import com.ja.openchat.viewmodels.ForwardViewModel;
import com.ja.openchat.views.CustomEditText;
import com.ja.openchat.views.PostContactDialog;
import com.ja.openchat.views.UserAvatarView;
import com.nanchen.compresshelper.CompressHelper;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.file.DocumentInfo;
import com.zy.openchat.core.model.group.GroupManagePermissionInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.ForwardInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.VideoParam;
import com.zy.openchat.core.model.photo.PhotoInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.zy.openchat.util.AndroidBug5497Workaround;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.FileUtils;
import com.zy.openchat.util.MediaUtils;
import com.zy.openchat.util.glide.GlideApp;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseActivity;


public class ForwardActivity extends BaseActivity<ActivityForwardBinding, ForwardViewModel> {
    private List<MessageInfo> messages;

    public static final String BUNDLE_OUTER_PATH = "bundle_outer_path";
    public static final String BUNDLE_OUTER_TEXT = "bundle_outer_text";

    public static final String BUNDLE_REMOTE_VIDEO = "bundle_remote_video";
    public static final String BUNDLE_REMOTE_PHOTO = "bundle_remote_photo";

    private BaseQuickAdapter<ForwardInfo, BaseViewHolder> mAdapter;
    private String outerFilePath;
    private String outerText;

    private PhotoInfo remotePhotoInfo;
    private VideoInfo remoteVideoInfo;
    private boolean isMore = false;

    private int totalNum;
    private int tempNum;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_forward;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public ForwardViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ForwardViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        onDidCreate();
    }

    private long onlyChatId = 0;

    protected void onDidCreate() {
        AndroidBug5497Workaround.assistActivity(this);

        Intent arguments = getIntent();
        if (arguments == null) {
            finish();
        }
        outerFilePath = arguments.getStringExtra(BUNDLE_OUTER_PATH);
        outerText = arguments.getStringExtra(BUNDLE_OUTER_TEXT);
        onlyChatId = arguments.getLongExtra("only_chat_id", 0);
        if (TextUtils.isEmpty(outerFilePath) && TextUtils.isEmpty(outerText)) {
            messages = arguments.getParcelableArrayListExtra("messages");
            if (messages == null || messages.isEmpty()) {
                MessageInfo message = arguments.getParcelableExtra("message");
                if (message != null) {
                    messages = new ArrayList<>();
                    messages.add(message);
                }
            }
            if (Common.isEmpty(messages)) {
                remotePhotoInfo = getIntent().getParcelableExtra(BUNDLE_REMOTE_PHOTO);
                remoteVideoInfo = getIntent().getParcelableExtra(BUNDLE_REMOTE_VIDEO);
                if (remotePhotoInfo == null && remoteVideoInfo == null) {
                    finish();
                }

            }
        }
        mAdapter = new BaseQuickAdapter<ForwardInfo, BaseViewHolder>(R.layout.adapter_contact_list) {
            @Override
            protected void convert(@NotNull BaseViewHolder helper, ForwardInfo info) {
                UserAvatarView iv_icon = helper.getView(R.id.iv_icon);
                if (info.chatInfo != null) {
                    if (info.chatInfo.isGroup()) {
                        iv_icon.showGroup(info.chatInfo);
                        helper.setText(R.id.iv_title, info.chatInfo.title);
                    } else {
                        iv_icon.showUser(UserInfo.getUserInfo(info.chatInfo.userId()));
                        helper.setText(R.id.iv_title, UserInfo.userDisplayName(info.chatInfo.userId()));
                    }
                } else if (info.userInfo != null) {
                    iv_icon.showUser(info.userInfo);
                    helper.setText(R.id.iv_title, info.userInfo.displayName());
                }
                View view = helper.getView(R.id.checkView);
                if (isMore) {
                    view.setVisibility(View.VISIBLE);
                } else {
                    view.setVisibility(View.GONE);
                }

                view.setSelected(info.isSelect);

            }
        };
        viewModel.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                if(isMore){
                    //多选 进行点击选择
                    ForwardInfo info = (ForwardInfo) adapter.getData().get(position);
                    info.isSelect = !info.isSelect;
                    mAdapter.notifyDataSetChanged();
                    int num = 0;
                    for (int i = 0; i < mAdapter.getData().size(); i++) {
                        ForwardInfo bean = (ForwardInfo) adapter.getData().get(i);
                        if(bean.isSelect){
                            num++;
                        }
                    }
                    if(num > 0){
                        binding.toolbar.tvOkRight1.setVisibility(View.GONE);
                        binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
                        binding.toolbar.tvOkRight.setText("发送("+num+")");
                    }else {
                        binding.toolbar.tvOkRight1.setVisibility(View.VISIBLE);
                        binding.toolbar.tvOkRight.setVisibility(View.GONE);
                        binding.toolbar.tvOkRight.setText("发送");
                    }
                }else {
                    //单选点击  直接发送
                    sendPosition(mAdapter.getItem(position),true);
                }
            }
        });
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(mAdapter);

//        KeyboardUtils.showSoftInput(etSearch);
        //输入框监听
        binding.etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initList();
        boolean isCanMore = true;
        if (messages != null && messages.size() == 1) {
            MessageInfo messageInfo = messages.get(0);
            if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Contact){
                //个人名片，只能单选发
                isCanMore = false;
            }
        }else if(messages != null && messages.size() > 1){
            //有多个  判断有没有名片
            for (int i = 0; i <messages.size(); i++) {
                MessageInfo messageInfo = messages.get(i);
                if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Contact){
                    //个人名片，只能单选发
                    isCanMore = false;
                }
            }
        }else {
            isCanMore = false;
        }

        binding.toolbar.tvBarTitle.setText(getString(R.string.choose_chat));
        isMore = false;
        if(isCanMore){
            //可多选
            binding.toolbar.tvOkRight1.setText("多选");
            binding.toolbar.tvOkRight1.setVisibility(View.VISIBLE);
            binding.toolbar.tvOkRight.setText(getString(R.string.send_text));
            binding.toolbar.tvOkRight.setBackgroundResource(R.drawable.login_btn_bg_green_90);
        }else {
            binding.toolbar.tvOkRight1.setVisibility(View.GONE);
            binding.toolbar.tvOkRight.setVisibility(View.GONE);
        }

        binding.toolbar.tvOkRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<ForwardInfo> data = mAdapter.getData();
                List<ForwardInfo> list = new ArrayList<>();
                List<ForwardInfo> listGroup = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    ForwardInfo forwardInfo = data.get(i);
                    if (forwardInfo.isSelect) {
                        if(forwardInfo.chatInfo != null && forwardInfo.chatInfo.isSuperGroup()){
                            listGroup.add(forwardInfo);
                        }else {
                            list.add(forwardInfo);
                        }
                    }
                }
                totalNum = list.size()+listGroup.size();
                tempNum = 0;
                for (int i = 0; i < listGroup.size(); i++) {
                    ForwardInfo forwardInfo = listGroup.get(i);
                    sendPosition(forwardInfo,false);
                }
                for (int i = 0; i < list.size(); i++) {
                    ForwardInfo forwardInfo = list.get(i);
                    if(i == list.size()-1){
                        //最后一个发完关闭
                        sendPosition(forwardInfo,true);
                    }else {
                        sendPosition(forwardInfo,false);
                    }
                }
            }
        });

        binding.toolbar.tvOkRight1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isMore){
                    //多选
                    isMore = true;
                    binding.toolbar.tvOkRight1.setText("单选");
                    binding.toolbar.tvBarTitle.setText("选择多个聊天");

                    if(mAdapter != null){
                        int num = 0;
                        for (int i = 0; i < mAdapter.getData().size(); i++) {
                            ForwardInfo bean = (ForwardInfo) mAdapter.getData().get(i);
                            if(bean.isSelect){
                                num++;
                            }
                        }
                        if(num > 0){
                            binding.toolbar.tvOkRight1.setVisibility(View.GONE);
                            binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
                            binding.toolbar.tvOkRight.setText("发送("+num+")");
                        }else {
                            binding.toolbar.tvOkRight1.setVisibility(View.VISIBLE);
                            binding.toolbar.tvOkRight.setVisibility(View.GONE);
                            binding.toolbar.tvOkRight.setText("发送");
                        }
                    }

                }else {
                    //单选
                    isMore = false;
                    binding.toolbar.tvOkRight1.setText("多选");
                    binding.toolbar.tvBarTitle.setText(getString(R.string.choose_chat));

                }
                if(mAdapter != null){
                    mAdapter.notifyDataSetChanged();
                }


            }
        });

    }

    public void sendPosition(ForwardInfo forwardInfo, boolean isLast) {

        if (forwardInfo.chatInfo != null) {
            if (forwardInfo.chatInfo.isSuperGroup()) {
                TelegramManager.getTelegramManager().getSuperGroupInfo(getBaseContext(), forwardInfo.chatInfo.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                        if (messageViewModel == null) {
                            messageViewModel = ViewModelProviders.of(ForwardActivity.this).get(MessageViewModel.class);
                        }
                        messageViewModel.setSuperGroupInfo(obj);
                        goGroupForward(forwardInfo,isLast);
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        goGroupForward(forwardInfo,isLast);
                    }
                });
            } else {
                forward(forwardInfo.chatInfo,isLast);
            }
        } else if (forwardInfo.userInfo != null) {
            TelegramManager.getTelegramManager().createPrivateChat(getBaseContext(), forwardInfo.userInfo.id, new TgResultBlock<ChatInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                    if (obj != null) {
                        forward(obj,isLast);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }
    }

    private void goGroupForward(ForwardInfo forwardInfo,boolean isLast) {
        TelegramManager.getTelegramManager().updateChatInfoChatPermession(this, forwardInfo.chatInfo, false, new TgResultBlock<GroupManagePermissionInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, GroupManagePermissionInfo obj) {
                forward(forwardInfo.chatInfo,isLast);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    public List<ForwardInfo> searchTotalList = new ArrayList<>();

    private List<ForwardInfo> publicChatsList = new ArrayList<>();

    private List<ForwardInfo> localList = new ArrayList<>();

    private boolean isLocalContainUser(UserInfo userInfo) {
        if (userInfo == null || localList.isEmpty()) {
            return false;
        }
        for (ForwardInfo forwardInfo : localList) {
            if (forwardInfo.chatInfo != null && forwardInfo.chatInfo.isSecretChat() && forwardInfo.chatInfo.userId() == userInfo.id) {
                return true;
            }
        }
        return false;
    }

    public void doSearch(String keyword) {
        publicChatsList.clear();
        localList.clear();
        if (TextUtils.isEmpty(keyword)) {
            mAdapter.setNewInstance(mTotalList);
            return;
        }
        for (ForwardInfo forwardInfo : mTotalList) {
            if (forwardInfo.chatInfo != null && forwardInfo.chatInfo.isMatch(keyword)) {
                localList.add(forwardInfo);
            }
        }
        List<UserInfo> list = TelegramManager.getTelegramManager().getTgData().getMyContacts(keyword);
        if (list != null && list.size() > 0 && onlyChatId == 0) {
            for (UserInfo userInfo : list) {
                if (!isLocalContainUser(userInfo)) {
                    publicChatsList.add(new ForwardInfo(userInfo));
                }
            }
        }

        reloadChatList();
    }

    private void reloadChatList() {
        searchTotalList.clear();
        searchTotalList.addAll(localList);
        searchTotalList.addAll(publicChatsList);
        mAdapter.setNewInstance(searchTotalList);
    }

    private List<ForwardInfo> mTotalList = new ArrayList<>();

    private void initList() {
        List<ChatInfo> list = TelegramManager.getTelegramManager().getTgData().getChatList();
        if (list != null && list.size() > 0) {
            Collections.sort(list, new Comparator<ChatInfo>() {
                @Override
                public int compare(ChatInfo ct1, ChatInfo ct2) {
                    return Long.compare(ct2.modifyDate(), ct1.modifyDate());
                }
            });
            Collections.sort(list, new Comparator<ChatInfo>() {
                @Override
                public int compare(ChatInfo ct1, ChatInfo ct2) {
                    return Long.compare(ct2.is_pinned ? 1 : 0, ct1.is_pinned ? 1 : 0);
                }
            });
            for (ChatInfo chat : list) {
                //我的收藏-不显示
                if (!chat.isGroup() && chat.id == UserInfo.getUserInfo().id) {
                    list.remove(chat);
                    break;
                }
            }
            mTotalList.clear();
            for (ChatInfo chat : list) {
                if (onlyChatId != 0) {
                    if (onlyChatId == chat.id) {
                        mTotalList.add(new ForwardInfo(chat));
                    }
                } else {
                    if (chat.lastMessage != null) {
                        mTotalList.add(new ForwardInfo(chat));
                    }
                }
            }

        }
        mAdapter.setNewInstance(mTotalList);
    }

    private MessageViewModel messageViewModel;

    public void forward(ChatInfo conversation,boolean isLast) {
        if (messageViewModel == null) {
            messageViewModel = ViewModelProviders.of(this).get(MessageViewModel.class);
        }
        tempNum ++;
        if(tempNum == totalNum){
            isLast = true;
        }else {
            isLast = false;
        }
        if (!Common.isEmpty(messages)) {
            if (conversation.isSuperGroup()) {
                if (messageViewModel.canEditGroupSetting()) {
                    if (messages != null && messages.size() == 1) {
                        MessageInfo messageInfo = messages.get(0);
                        if (messageInfo.messageType == TelegramManager.MessageType.MessageType_Contact && messageInfo.content != null && messageInfo.content.contact != null) {
                            UserInfo userInfo = UserInfo.getUserInfo(messageInfo.content.contact.user_id);
                            if (userInfo != null) {
                                PostContactDialog.show(ForwardActivity.this, userInfo, new OnContactSendListener() {
                                    @Override
                                    public void toSend(String content) {
                                        if (messageInfo.id <= 0) {
                                            messageViewModel.sendContactMsg(conversation, userInfo);
                                        } else {
                                            TelegramManager.getTelegramManager().forwardMessages(ForwardActivity.this, conversation.id, messages);
                                        }

                                        if (!TextUtils.isEmpty(content)) {
                                            messageViewModel.sendTextMsg(conversation, content);
                                        }
                                        ChatActivity.startActivity(ForwardActivity.this, conversation);
                                        ForwardActivity.this.finish();
                                    }
                                });
                                return;
                            }
                        }
                    }
                    TelegramManager.getTelegramManager().forwardMessages(this, conversation.id, messages);
                } else {
                    for (MessageInfo messageInfo : messages) {
                        if (messageInfo.messageType == TelegramManager.MessageType.MessageType_Text) {
                            if (messageViewModel.canSendTextMsg(conversation, messageInfo.toString())) {
                                TelegramManager.getTelegramManager().forwardMessage(conversation.id, messageInfo);
                            }
                        } else if (messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo
                                || messageInfo.messageType == TelegramManager.MessageType.MessageType_Audio
                                || messageInfo.messageType == TelegramManager.MessageType.MessageType_Video
                                || messageInfo.messageType == TelegramManager.MessageType.MessageType_Document
                                || messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation
                                || messageInfo.messageType == TelegramManager.MessageType.MessageType_Voice_Note) {
                            if (messageViewModel.canSendMediaMsg(conversation)) {
                                if (messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo) {
                                    if (conversation != null && conversation.permissions != null && conversation.permissions.banSendQRcode) {
                                        if (!TextUtils.isEmpty(messageInfo.messagePhotoLocalPath())) {
                                            GlideApp.with(ForwardActivity.this)
                                                    .asBitmap()
                                                    .load(messageInfo.messagePhotoLocalPath())
                                                    .into(new SimpleTarget<Bitmap>() {
                                                        @Override
                                                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                            if (messageViewModel.canSendQrImg(conversation, resource)) {
                                                                TelegramManager.getTelegramManager().forwardMessage(conversation.id, messageInfo);
                                                            }
                                                        }
                                                    });
                                        } else {

                                        }
                                    } else {
                                        TelegramManager.getTelegramManager().forwardMessage(conversation.id, messageInfo);
                                    }
                                } else {
                                    TelegramManager.getTelegramManager().forwardMessage(conversation.id, messageInfo);
                                }
                            }
                        } else if (messageInfo.messageType == TelegramManager.MessageType.MessageType_Contact) {
                            if (messageInfo.content != null && messageInfo.content.contact != null) {
                                UserInfo userInfo = UserInfo.getUserInfo(messageInfo.content.contact.user_id);
                                if (userInfo != null) {
                                    PostContactDialog.show(ForwardActivity.this, userInfo, new OnContactSendListener() {
                                        @Override
                                        public void toSend(String content) {
                                            if (messageInfo.id <= 0) {
                                                messageViewModel.sendContactMsg(conversation, userInfo);
                                            } else {
                                                TelegramManager.getTelegramManager().forwardMessages(ForwardActivity.this, conversation.id, messages);
                                            }
                                            if (!TextUtils.isEmpty(content)) {
                                                messageViewModel.sendTextMsg(conversation, content);
                                            }
                                            ChatActivity.startActivity(ForwardActivity.this, conversation);
                                            ForwardActivity.this.finish();
                                        }
                                    });
                                    return;
                                }
                            }
                        }
                    }
                }
            } else {
                if (messages != null && messages.size() == 1) {
                    MessageInfo messageInfo = messages.get(0);
                    if (messageInfo.messageType == TelegramManager.MessageType.MessageType_Contact && messageInfo.content != null && messageInfo.content.contact != null) {
                        UserInfo userInfo = UserInfo.getUserInfo(messageInfo.content.contact.user_id);
                        if (userInfo != null) {
                            PostContactDialog.show(ForwardActivity.this, userInfo, new OnContactSendListener() {
                                @Override
                                public void toSend(String content) {
                                    if (messageInfo.id <= 0) {
                                        messageViewModel.sendContactMsg(conversation, userInfo);
                                    } else {
                                        TelegramManager.getTelegramManager().forwardMessages(ForwardActivity.this, conversation.id, messages);
                                    }
                                    if (!TextUtils.isEmpty(content)) {
                                        messageViewModel.sendTextMsg(conversation, content);
                                    }
                                    ChatActivity.startActivity(ForwardActivity.this, conversation);
                                    ForwardActivity.this.finish();
                                }
                            });
                            return;
                        }
                    }
                }
                TelegramManager.getTelegramManager().forwardMessages(this, conversation.id, messages);
            }
            if(isMore ){
                if(isLast){
                    ChatActivity.startActivity(this, conversation);
                }
            }else {
                ChatActivity.startActivity(this, conversation);
            }
        } else if (!TextUtils.isEmpty(outerFilePath) || !TextUtils.isEmpty(outerText)) {

            if (!TextUtils.isEmpty(outerFilePath)) {
                if (DocumentInfo.isImageFile(outerFilePath)) {
                    showProgress();
                    boolean finalIsLast = isLast;
                    Observable.create(new ObservableOnSubscribe<String>() {
                                @Override
                                public void subscribe(@NotNull ObservableEmitter<String> emitter) throws Exception {
                                    File newFile = new CompressHelper.Builder(ForwardActivity.this).setMaxWidth(1440).setMaxHeight(2880).build().compressToFile(new File(outerFilePath));
                                    emitter.onNext(newFile.getAbsolutePath());
                                    emitter.onComplete();
                                }
                            }).subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<String>() {
                                @Override
                                public void accept(String first) throws Exception {
                                    GlideApp.with(ForwardActivity.this)
                                            .asBitmap()
                                            .load(first)
                                            .into(new SimpleTarget<Bitmap>() {
                                                @Override
                                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                    messageViewModel.sendImgMsg(conversation, first, resource, resource.getWidth(), resource.getHeight());
                                                }
                                            });

                                }
                            }, new Consumer<Throwable>() {
                                @Override
                                public void accept(Throwable throwable) throws Exception {
                                    hideProgress();
                                    throwable.printStackTrace();
                                }
                            }, new Action() {
                                @Override
                                public void run() throws Exception {
                                    hideProgress();
                                    if(isMore){
                                        if(finalIsLast){
                                            ChatActivity.startActivity(ForwardActivity.this, conversation);
                                            ForwardActivity.this.finish();
                                        }
                                    }else {
                                        ChatActivity.startActivity(ForwardActivity.this, conversation);
                                        ForwardActivity.this.finish();
                                    }
                                }
                            });

                } else if (DocumentInfo.isVideoFile(outerFilePath)) {
                    VideoParam videoParam = MediaUtils.getVideoParam(outerFilePath);
                    if (videoParam != null) {
//                        if (videoParam.getDuration() > 30) {
//                            ToastUtils.showShort("不支持发送超过时长30s的视频");
//                            return;
//                        }
                        messageViewModel.sendVideoMsg(conversation, outerFilePath, videoParam.getDuration(), videoParam.getWidth(), videoParam.getHeight());
                    }
                    if(isMore){
                        if(isLast){
                            ChatActivity.startActivity(ForwardActivity.this, conversation);
                            ForwardActivity.this.finish();
                        }
                    }else {
                        ChatActivity.startActivity(ForwardActivity.this, conversation);
                        ForwardActivity.this.finish();
                    }

                } else {
                    File file = new File(outerFilePath);
                    if (file.length() > BuildConfig.SendFileMaxSize) {
                        ToastUtils.showShort(String.format(getString(R.string.file_size_max_warn), FileUtils.getReadableFileSize(BuildConfig.SendFileMaxSize)));
                        return;
                    }
                    messageViewModel.sendFileMessage(conversation, file);
                    if(isMore){
                        if(isLast){
                            ChatActivity.startActivity(ForwardActivity.this, conversation);
                            ForwardActivity.this.finish();
                        }
                    }else {
                        ChatActivity.startActivity(ForwardActivity.this, conversation);
                        ForwardActivity.this.finish();
                    }
                }
            } else {
                messageViewModel.sendTextMsg(conversation, outerText);
                if(isMore){
                    if(isLast){
                        ChatActivity.startActivity(ForwardActivity.this, conversation);
                        ForwardActivity.this.finish();
                    }
                }else {
                    ChatActivity.startActivity(ForwardActivity.this, conversation);
                    ForwardActivity.this.finish();
                }
            }


        } else if (remotePhotoInfo != null) {
            messageViewModel.sendRemotePhoto(conversation, remotePhotoInfo);
            if(isMore){
                if(isLast){
                    ChatActivity.startActivity(ForwardActivity.this, conversation);
                    ForwardActivity.this.finish();
                }
            }else {
                ChatActivity.startActivity(ForwardActivity.this, conversation);
                ForwardActivity.this.finish();
            }
        } else if (remoteVideoInfo != null) {
            messageViewModel.sendVideoMsg(conversation, remoteVideoInfo);
            if(isMore){
                if(isLast){
                    ChatActivity.startActivity(ForwardActivity.this, conversation);
                    ForwardActivity.this.finish();
                }
            }else {
                ChatActivity.startActivity(ForwardActivity.this, conversation);
                ForwardActivity.this.finish();
            }
        }


    }


}
